import { Ref, onMounted, onUnmounted, ref } from "vue";

export function useHeaderFixed(
    headerRef: Ref<HTMLElement | null>,
    trigger: number = 0,
    timeout: number = 100,
) {
    const timer = ref<number>();
    const tiggerHeight = ref<number>(trigger);

    onMounted(() => {
        tiggerHeight.value = trigger || parseInt(getComputedStyle(headerRef.value as HTMLElement).height) + 30;

        headerRef.value = headerRef.value || document.querySelector('.m-header');
        window.addEventListener('scroll', handleScroll)
        dispatchEvent(new Event('scroll'))
    })
    onUnmounted(() => {
        window.removeEventListener('scroll', handleScroll)
    })

    function handleScroll() {
        clearTimeout(timer.value);
        timer.value = setTimeout(() => {
            if (!headerRef.value) return;
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            if (scrollTop > tiggerHeight.value && headerRef.value.style.position !== 'fixed') {
                headerRef.value.style.position = 'fixed';
                headerRef.value.style.top = '0px';
            }
            if(scrollTop === 0){
                headerRef.value.style.position = 'absolute';
            }
        }, timeout);
    }

    function stop() {
        clearTimeout(timer.value);
    }

    return {
        stop
    }

}